/**
 * 医生端我的收藏
 * Created by alice on 2016/7/12.
 */
require.config({
    baseUrl:'../js',
    paths:{
        "getData":"Util/getData",
        "config":"common/config",
        "components":"common/components",
        "common":"common/common",
        "jquery":"lib/jquery.min",
        "iscroll":"lib/iscroll",
        "pullToRefresh":"lib/pullToRefresh",
        "wx":"lib/jweixin-1.0.0"
    },
    shim : {
        "components": { deps : ["jquery"] }
    },
    urlArgs: "v=" + (new Date()).getTime()//以禁用浏览器缓存,上线后注释掉
});
require(['jquery','getData','config','common','components','iscroll','pullToRefresh','wx'],function($,getData,config,common,components,iscroll,pullToRefresh,wx){

    var refresher=pullToRefresh.refresher;
    var gm=common.gm;
    var getuuid=gm.para.get(window.location.href,"doctorUuid");
    var token=gm.para.get(window.location.href,"token");
    /*if(!gm.common.isObjUsable(getuuid)){
        $("#my_collection .listview_left_del").html('<p id="dont_show">您目前还没有收藏文章和视频！</p>');
        return ;
    }*/
    /**
     * 收藏为空时，进入V医讲堂
     */
    $(".goto_all_course a").bind({
        touchend:function(){
            console.log(token);
            window.location.href="all_course.html?title=V医讲堂&token="+token;
        }
    });
    /**
     * 收藏为空时进入知识文献
     */
    $(".goto_read a").bind({
        touchend:function(){
            console.log(token);
            window.location.href="read.html?title=知识文献&token="+token;
        }
    });
    /**分页功能**/

    var generatedCount = 1;
    var totalPage=0;
    //获取我的收藏
    getData.getJson({
        page:"content",
        loading:true,
        inter:"getCommonCollectionList",
        data:{token:token,collectRule:0,pageSize:15,pageNum:1},
        callback:function(data){
            if(!data){
                $.alert("服务器出错!");
            }
            var getdata=data.value;
            if(getdata==undefined || getdata==null || getdata.length==0){
                $(".empty_collection").show();
                return ;
            }
            if(data.code=="2000"){
                $(".listview_left_del ul").html(getStrData(getdata).join(""));//填充数据
                if(getdata.length>=20){
                    refresher.init({
                        id:"wrapper",//
                        pullDownAction:Refresh,
                        pullUpAction:Load
                    });
                    totalPage=data.total;
                    wrapper.refresh();
                }
                bindevent();
            }else{
                components.alert(data.message);
            }
        }
    });

    /**
     * 刷新
     * @constructor
     */
    function Refresh() {
        setTimeout(function () {	// <-- Simulate network congestion, remove setTimeout from production!
           var ____loading = new components.mask("loading");
            ____loading.show();
            refreshdata(20,1,function(data){
                ____loading.hide();
                $(".listview_left_del ul").html(getStrData(data).join(""));
                bindevent();
                generatedCount=1;
                totalPage=data.total;
                if(totalPage<=1)
                    $(".pullUp").remove();
                else
                    $(".scroller").append("<div class='pullUp'><div class='loader'><span></span><span></span><span></span><span></span></div><div class='pullUpLabel'>上拉加载 更多...</div></div>");
                $(".pullUp").show();
                wrapper.refresh();
            });
        }, 1000);

    }

    /**
     * 加载
     * @constructor
     */
    function Load() {
        setTimeout(function () {// <-- Simulate network congestion, remove setTimeout from production!
            ++generatedCount;
            if(generatedCount<=totalPage)
                refreshdata(20,generatedCount,function(data){
                    $(".listview_left_del ul").append(getStrData(data).join(""));
                    bindevent();
                    if(generatedCount==data.total)
                        $(".pullUp").remove();
                    wrapper.refresh();
                });
            else
                $(".pullUp").hide();
        }, 1000);
    }
    /**
     * 收藏页面加载更多时调用
     * @param page 当前页面有多少条记录
     * @param pageno 当前第几页面
     * @param callback
     */
    function refreshdata(page,pageno,callbak){
        getData.getJson({
            page:"content",
            inter:"getCommonCollectionList",
            data:{token:token,collectRule:0,pageSize:page,pageNum:pageno},
            callback:function(data){
                callbak && callbak(data);
            }
        });
    }
//分页功能结束


    //后退到个人中心

    gm.pul.returnurl=function(){
        gm.pul.toUrl('/html/user/index.shtml');
    };

    /**
     * 删除收藏的调用
     * @param obj
     * @param type
     * @returns {boolean}
     */
    function deleteCollect(obj,type){
        var that=this;
        components.confirm("确定要删除吗？",function(){
            var collectType=obj.attr("favoritetype");
            var objId=obj.attr("contentuuid");
            gm.common.delFavorites(token,collectType,objId,function(data){

                if(!data){
                    components.alert("服务器出错!");
                }
                if(data.code=="2000"){
                    components.alert({
                        "val" : "删除成功", "type" : "flash" , "callback" : function(){
                            obj.fadeOut(500);
                            obj.remove();
                            if($("ul li.isopen").length==0)
                                $(".empty_collection").show();
                            //判断收藏的内容是否还有
                            /* var len=$(".listview_left_del ul li").length;
                             if(len!=null && len<=1)
                             $(".varioustype").html('<p id="dont_show">您目前还没有收藏文章和视频！</p>');*/
                        }
                    });
                }else{
                    components.alert(data.message);
                }
            });

        },function(){//取消删除
            obj.children(".restore_left_slip").attr('data-box-status',0);
            obj.children(".restore_left_slip").css({"transform":"translate3d(0rem, 0px, 0px)"});
        });
        return false;
    }
    /**
     * 拼装html str,并返回arr
     * @param data
     */
    function getStrData(data){
        var arr = [];
        var tmp='<li class="isopen" favoriteUuid="{favoriteUuid}" contentUuid="{objId}" favoriteType="{collectType}" value="{url}">\
                    <div class="restore_left_slip asbg" data-box-status="0" style="transition: all 0.1s ease; transform: translate3d(0rem, 0px, 0px);">\
                        <div class="live">\
                            <img src="{image}">\
                        </div>\
                        <div class="text">\
                            <div class="collectionContentTitle"><p>{titleName}</p></div>\
                            <p class="time">\
                                {collectNum}{commonNum}\
                            </p>\
                        </div>\
					</div>\
				</li>';
        $(data).each(function(i,o){
            var imgstr=o.image;
            o.image = gm.common.isObjUsable(imgstr)?(imgstr.substr(0,7)=="http://"?imgstr:window._interfaceImgPath+""+imgstr):window.___defaultImage;


            var faritetype=o["collectType"];
            //是否收藏
            var isCollection=1;
            var title= o.titleName;
            var desc= o.titleName;
            var img= o.imageUrl;
            var favoriteType=faritetype;
            var favoriteUuid= o.objId;
            var collectRule=0;
            var str="isCollection="+isCollection+"&title="+title+"&desc="+desc+"&img="+img+"&contentType="+favoriteType+"&token="+token+"&favoriteUuid="+favoriteUuid+"&collectRule="+collectRule;


            if(faritetype==0){
                o.url='informationfordetails.html?client=ios&contentUuid='+o["objId"]+"&"+str;
            }else if(faritetype==1){
                o.url='playing.html?client=ios&vidoUuid='+o["objId"]+"&"+str;
            }else
                components.alert("未知数据！");

            if(faritetype==0){
                var collectNum=gm.common.isObjUsable(o.collectNum);
                o.collectNum=collectNum?"<span style='margin-right: .5rem;'>收藏 "+o.collectNum+"</span>":"<span style='margin-right: .5rem;'>收藏 0</span>";//判断收藏字段是否存在
                o.commonNum= o.readNum?"<span style='margin-right: .5rem;'>阅读 "+o.readNum+"</span>":"<span style='margin-right: .5rem;'>阅读 0</span>";//判断阅读字段是否存在
            }else if(faritetype==1){
                var collectNum=gm.common.isObjUsable(o.collectNum);
                o.collNumber=collectNum?"<span style='margin-right: .5rem;'>收藏 "+o.collectNum+"</span>":"<span style='margin-right: .5rem;'>收藏 0</span>";//判断收藏字段是否存在
                var commonNum=gm.common.isObjUsable(o.commonNum);
                o.commonNum=commonNum?"<span style='margin-right: .5rem;'>评论 "+o.commonNum+"</span>":"<span style='margin-right: .5rem;'>评论 0</span>";//判断评论字段是否存在
            }
            arr.push(gm.replace(tmp,o));
        });
        return arr;
    }

    /**
     * 绑定事件
     */
    function bindevent(){
        //$(".listview_left_del ul li > div:nth-child(1)").lrTouchMove();
        $(".listview_left_del ul li").bind({
            touchend:function(e){
                e.preventDefault();
            }
        });
        $(".listview_left_del ul li").ontouch(function(){
            var url=$(this).attr("value");
            if(url!=undefined && url!=null && url!="")
                gm.pul.toUrl(url);
            },true
        );

        $(".ndh_del").ontouch(function(e){
            var obj = $(this).parent().parent();
            var type = "delete";
            deleteCollect(obj,type);
        },true);
    }
});